package com.itheima.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/addStudent")
public class AddStudentServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决post 请求的中文乱码问题
        req.setCharacterEncoding("utf-8");
        resp.setHeader("Content-Type","text/html;charset=utf-8");

        //获取前段传过来的各种信息
        String name = req.getParameter("name");
        String ageStr = req.getParameter("age");
        String scoreStr = req.getParameter("score");
        //保存到本地
        //创建本地输出流
        BufferedWriter writer = new BufferedWriter(new FileWriter("G://stu.txt",true));
        //写数据
        writer.write(name+","+ageStr+","+scoreStr);
        writer.newLine();
        //释放资源
        writer.close();
        //给前端提示
        PrintWriter writer1 = resp.getWriter();
        writer1.write("保存成功,2秒后跳转首页");
      //  writer1.close();
        resp.setHeader("Refresh","2;URL=/studentsystem/index.jsp");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
